import java.util.concurrent.Semaphore;

public class DiningPhilosophers {
    private Semaphore[] sema;
    public DiningPhilosophers() {
        sema = new Semaphore[] {
                new Semaphore(1),
                new Semaphore(1),
                new Semaphore(1),
                new Semaphore(1),
                new Semaphore(1)
        };
    }

    // call the run() method of any runnable to execute its code
    public void wantsToEat(int philosopher,
                           Runnable pickLeftFork,
                           Runnable pickRightFork,
                           Runnable eat,
                           Runnable putLeftFork,
                           Runnable putRightFork) throws InterruptedException {
        //要是每个人都只获取到了一个叉子就死锁了
        synchronized (this) {
            sema[philosopher].acquire();
            sema[(philosopher + 1) % 5].acquire();
        }
        pickLeftFork.run();
        pickRightFork.run();
        eat.run();
        putLeftFork.run();
        putRightFork.run();
        //放下叉子不用锁
        sema[philosopher].release();
        sema[(philosopher+1) % 5].release();
    }
}
